import {
	defineStore
} from 'pinia'
export const appStore = defineStore('app', {
	unistorage: true, // 是否持久化到内存
	state: () => {
		return {
			// 测试
			appIndex: 999,
      cart:JSON.parse(uni.getStorageSync('cart') || '[]')
		}
	},
	actions: {
    addToCart(goods){
      const findResult = this.cart.find((x) => x.goods_id === goods.goods_id )
      if(!findResult){
        this.cart.push(goods)
      }else{
        findResult.goods_count++
      }
      this.saveToStorage()
    },
    saveToStorage(){
      uni.setStorageSync('cart',JSON.stringify(this.cart))
    },
    setTabBar(){
      uni.setTabBarBadge({
        index:2,
        text:this.checkedCount + ''
      })
    },
    changeCartStateById(goods_id,goods_state){
      const findResult = this.cart.find((x) => x.goods_id === goods_id)
      if(findResult){
        findResult.goods_state = goods_state
      }
      this.saveToStorage()
    },
    changeGoodsCountById(goods_id,goods_count){
      const findResult = this.cart.find((x) => x.goods_id === goods_id)
      if(findResult) {
        findResult.goods_count = goods_count
      }
      this.saveToStorage()
    },
    delGoodsById(goods_id){
      this.cart = this.cart.filter(x => x.goods_id !== goods_id)
      this.saveToStorage()
    },
    updateGoodsState(newState){
      this.cart.forEach(x => x.goods_state = newState)
    },
    
  },
  getters:{
    cartTotal(){
      return this.cart.reduce((total,item) => total += item.goods_count,0)
    },
    checkedCount(){
      return this.cart.filter(x => x.goods_state).reduce((total,item) => total += item.goods_count,0)
    },
    checkedGoodsAmount(){
      return this.cart.filter(x => x.goods_state).reduce((total,item) => total += item.goods_count*item.goods_price,0).toFixed(2)
    }
  },
  
  
})
